package com.tuo51.evaluate.service.impl;


import com.tuo51.evaluate.service.RemoteChartService;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;


@Service
public class RemoteChartServiceImpl implements RemoteChartService {

    @Value("${chart_server.url}")
    private String chartServerURL;

    @Override
    public String getRemoteEvaluateChartBase64(Double[] barValues) {
        byte[] result = getRemoteEvaluateChart(barValues);

        String data = DatatypeConverter.printBase64Binary(result);

        return data;
    }

    @Override
    public byte[] getRemoteEvaluateChart(Double[] barValues) {
        String JSON_TEMPLATE = "{\"infile\":{\"credits\":{\"enabled\":false},\"chart\":{\"type\":\"column\"," +
                "\"width\":\"946\",\"height\":\"460\"},\"title\":{\"text\":\"\",\"enabled\":false},\"xAxis\":" +
                "{\"categories\":[\"发展能区\",\"精细动作\",\"适应能力\",\"语言\",\"社会行为\",\"大运动\",\"综合评价\"]," +
                "\"labels\":{\"rotation\":-45,\"style\":{\"fontSize\": \"18px\",\"fontFamily\": \"Microsoft YaHei\"}}}," +
                "\"yAxis\":[{\"min\":0,\"max\":150,\"title\":{\"text\":\"发育商\"},\"stackLabels\":{\"enabled\":true,\"" +
                "style\":{\"shadow\":false,\"fontWeight\":\"normal\",\"color\":\"#787878\",\"textOutline\":\"0px\"}}}," +
                "{\"min\":0,\"max\":150,\"title\":{\"text\":\"上次测评 (2019-11-01)\",\"enabled\":false},\"stackLabels\":{\"enabled\":false}," +
                "\"opposite\":true},{\"min\":0,\"max\":150,\"title\":{\"text\":\"图例\",\"enabled\":false}," +
                "\"labels\":{\"enabled\":false},\"stackLabels\":{\"enabled\":false}}],\"legend\":{\"enabled\": true," +
                "\"floating\":false,\"align\": \"center\",\"verticalAlign\": \"bottom\",\"layout\": \"horizontal\"}," +
                "\"plotOptions\":{\"column\":{\"stacking\":\"normal\",\"dataLabels\":{\"enabled\":false}," +
                "\"grouping\":false,\"shadow\":false,\"borderWidth\":0}},\"series\":[{\"yAxis\":1,\"name\":\"上次测评\",\"showInLegend\": false," +
                "\"color\":\"rgba(165,170,217,0.3)\",\"data\":[0,0,0,0,0,0],\"pointPadding\":-0.1,\"pointPlacement\":1}," +
                "{\"yAxis\":2,\"showInLegend\": false,\"color\":\"#A3F680\",\"data\":[20]}," +
                "{\"yAxis\":2,\"showInLegend\": false,\"color\":\"#DDFD30\",\"data\":[15]}," +
                "{\"yAxis\":2,\"showInLegend\": false,\"color\":\"#FFFF00\",\"data\":[30]}," +
                "{\"yAxis\":2,\"showInLegend\": false,\"color\":\"#FFAB00\",\"data\":[15]}," +
                "{\"yAxis\":2,\"showInLegend\": false,\"color\":\"#FF8E00\",\"data\":[70]}," +
                "{\"name\":\"超常(130↑)\",\"color\":\"#A3F680\",\"data\":[%s]}," +
                "{\"name\":\"优秀(115 - 129)\",\"color\":\"#DDFD30\",\"data\":[%s]}," +
                "{\"name\":\"正常(85 - 114)\",\"color\":\"#FFFF00\",\"data\":[%s]}," +
                "{\"name\":\"落后(70 - 84)\",\"color\":\"#FFAB00\",\"data\":[%s]}," +
                "{\"name\":\"偏低(69 ↓)\",\"color\":\"#FF8E00\",\"data\":[%s]}]}}";

        if(barValues.length != 6){
            throw new BusinessException(ErrorCode.JSON_STR_ERROR, "传入数据错误");
        }

        double[] ranges = {130, 115, 85, 70, 0};
        for (int i = 0;i < 5; i++){
            int[] buffer = {0,0,0,0,0,0,0};
            double low = ranges[i];

            for (int j = 0; j < barValues.length; j++){
                if(barValues[j] >= low){
                    buffer[j+1] = (int)(barValues[j] + 0.5);
                    barValues[j] = Double.valueOf(0);
                }
            }

            String bs = String.format("%d,%d,%d,%d,%d,%d,%d", buffer[0], buffer[1], buffer[2], buffer[3], buffer[4], buffer[5], buffer[6]);

            JSON_TEMPLATE = StringUtils.replaceOnce(JSON_TEMPLATE, "%s" , bs);
        }
        //0,0,0,0,0,0,0
        return binaryHTTPCall(chartServerURL, JSON_TEMPLATE, "创建测评结果图表时异常");
    }

    private byte[] binaryHTTPCall(String url, String json, String errorMsg) {
        try {
            byte[] responseData = sendPostJson(url, json, "UTF-8");

            return responseData;
        } catch (BusinessException e){
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.UNDEFINED, errorMsg);
        }
    }

    public byte[] sendPostJson(String url, String params, String charset) throws IOException {
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestHeader("Content-Type", "application/json; charset=" + charset);
        if (params != null && !params.trim().equals("")) {
            RequestEntity requestEntity = new StringRequestEntity(params, "application/json", charset);
            postMethod.setRequestEntity(requestEntity);
        }

        HttpClient httpClient = new HttpClient();
        httpClient.executeMethod(postMethod);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(120000);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(120000);
        return postMethod.getResponseBody();
    }
}
